package com.example.interceptor;

import com.example.exception.UnauthorizedException;
import com.example.utils.JwtTokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    private final JwtTokenUtil jwtTokenUtil;

    public TokenInterceptor(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 Authorization 请求头
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new UnauthorizedException("Missing or invalid Authorization header");
        }

        // 提取 Token 部分
        String token = authHeader.substring(7);

        // 验证 Token
        if (!jwtTokenUtil.validateToken(token)) {
            throw new UnauthorizedException("Invalid or expired Token");
        }

        // 如果需要，可以将用户名存储到请求属性中，供后续使用
        String username = jwtTokenUtil.getUsernameFromToken(token);
        request.setAttribute("username", username);

        return true; // 验证通过
    }
}
